<template>
  <div class="panel">
    <div class="tool">
      <el-input v-model="kw" placeholder="搜索名称/编码" clearable style="max-width:260px" />
      <div class="right">
        <el-button text @click="expandAll(true)">展开全部</el-button>
        <el-button text @click="expandAll(false)">收起全部</el-button>
      </div>
    </div>

    <el-empty v-if="tree.length===0" description="暂无子层级" />

    <el-tree
      v-else
      ref="treeRef"
      node-key="id"
      :data="treeFiltered"
      :props="{ label: 'label', children: 'children' }"
      :default-expanded-keys="defaultExpands"
      highlight-current
      accordion
      class="tree"
    >
      <template #default="{ data }">
        <div class="node">
          <span class="name">{{ data.name }}</span>
          <el-tag size="small" type="info">{{ data.code || '-' }}</el-tag>
          <el-tag size="small" :type="typeTag(data.nodeType)">{{ typeText(data.nodeType) }}</el-tag>
          <el-button text size="small" @click.stop="$emit('open-detail', data.raw)">详情</el-button>
          <el-button text size="small" type="primary" @click.stop="$emit('open-edit', data.raw)">修改</el-button>
          <el-button text size="small" type="success" @click.stop="$emit('open-add-child', data.raw)">新增子项</el-button>
        </div>
      </template>
    </el-tree>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
  mother: Object,
  descendants: { type: Array, default: () => [] }
})
const kw = ref('')
const treeRef = ref()
const defaultExpands = ref([])

const tree = computed(() => {
  // 用 descendants 构建树（包含母机）
  const all = [{ ...props.mother, nodeType: props.mother?.nodeType || 'MACHINE' }, ...props.descendants]
  const map = new Map()
  all.forEach(r => map.set(r.id, { id:r.id, pid:r.pid, name:r.name, code:r.code, nodeType:r.nodeType, raw:r, children:[] }))
  const roots = []
  map.forEach(n => {
    const p = map.get(n.pid)
    if (p) p.children.push(n)
    else roots.push(n)
  })
  // label 统一
  const dfs = (n) => {
    n.label = n.code ? `${n.name}（${n.code}）` : n.name
    n.children?.forEach(dfs)
  }
  roots.forEach(dfs)
  defaultExpands.value = [props.mother?.id].filter(Boolean)
  return roots
})

const treeFiltered = computed(() => {
  const q = kw.value.trim().toLowerCase()
  if (!q) return tree.value
  const clone = (n) => {
    const hit = (n.name||'').toLowerCase().includes(q) || (n.code||'').toLowerCase().includes(q)
    const kids = (n.children||[]).map(clone).filter(Boolean)
    if (hit || kids.length) return { ...n, children:kids }
    return null
  }
  return tree.value.map(clone).filter(Boolean)
})

function expandAll(open) {
  const keys = []
  const walk = (arr) => arr.forEach(n => { keys.push(n.id); n.children?.length && walk(n.children) })
  walk(tree.value)
  treeRef.value?.setExpandedKeys(open ? keys : [])
}

function typeText(t='') {
  switch (t.toUpperCase()) {
    case 'MACHINE': return '母设备'
    case 'MODULE': return '子设备'
    case 'COMPONENT': return '部件'
    case 'PART': return '零件'
    default: return t || '—'
  }
}
function typeTag(t='') {
  return {MACHINE:'primary',MODULE:'success',COMPONENT:'warning',PART:'info'}[t.toUpperCase()] || 'info'
}
</script>

<style scoped>
.panel{ padding: 8px; }
.tool{ display:flex; justify-content:space-between; margin-bottom:8px; }
.node{ display:flex; align-items:center; gap:8px; }
.name{ font-weight:600; }
.tree{ background:#fff; padding:8px; border-radius:8px; }
</style>
